﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo10
{
    class Program
    {
        /// <summary>
        /// 计算每月还款金额，根据余下贷款的本金来计算利息
        /// 递归去算出剩余期数的还款额, 计算下一期还款的利息
        /// </summary>
        /// <param name="paymentPerMonth">每月还款金额</param>
        /// <param name="numberofPayment">还款期数</param>
        /// <returns></returns>
        static decimal CalTotalPayment(decimal paymentPerMonth,int numberofPayment)
        {
            // 当期数为0，结束递归
            if (numberofPayment == 0)
                return 0M;
            //递归调用，计算剩余期数的还款金额
            return paymentPerMonth + CalTotalPayment(paymentPerMonth, numberofPayment - 1);
        }

        /// <summary>
        /// 计算出总的本息还款金额
        /// </summary>
        /// <param name="principal">贷款本金</param>
        /// <param name="rate">年化利率</param>
        /// <param name="years">代款年数</param>
        /// <param name="paymentperYear">每年还款期数</param>
        /// <returns></returns>
        static decimal CalAmount(decimal principal,decimal rate,int years,int paymentperYear)
        {
            // 总还款期数=代款年数*每年还款期数  3年*12期=36期
            int numberofPayment = years * paymentperYear;
            // 每期还款利率=年化利率/每年还款期数
            decimal rateperPayment = rate / paymentperYear;
            //计算每月还款金额
            decimal paymentperMonth = (principal*rateperPayment*  
                (decimal)Math.Pow((double)(1+rateperPayment),   numberofPayment))
                / ((decimal)Math.Pow((double)(1+rateperPayment),  (numberofPayment-1)));
            //通过递归来计算出还款总额
            return principal+CalTotalPayment(paymentperMonth, numberofPayment);
        }
        static void Main(string[] args)
        {
            Console.WriteLine($"贷款本金1,000,000，年化利率3.9%。贷款年数20年，每年还款次数12次，总还款金额为{CalAmount(1000000M, 0.039M, 20, 12):c2}");
            Console.ReadKey();
        }
    }
}
